package com.ht.module.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.ht.abnormal.HtException;
import com.ht.constant.BusConstant;
import com.ht.constant.DicConstants;
import com.ht.constant.RedisConstants;
import com.ht.module.sys.dto.RegisterDto;
import com.ht.module.sys.entity.SysRole;
import com.ht.module.sys.entity.SysUser;
import com.ht.module.sys.entity.SysUserRole;
import com.ht.module.sys.service.ISysRoleService;
import com.ht.module.sys.service.ISysUserRoleService;
import com.ht.module.sys.service.ISysUserService;
import com.ht.util.JsonResult;
import com.ht.util.RedisUtil;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @ProjectName: ht
 * @ClassName: LoginController
 * @Author: hejialun
 * @Description: 登录相关接口
 * @Date: 2021/5/18 23:08
 */
@RestController
@RequestMapping("/sys-login")
@Api(tags = "登录相关接口 ")
public class LoginController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;


    @ApiModelProperty("注册用户")
    @PostMapping("/register")
    public JsonResult register(@RequestBody @Valid RegisterDto dto){
        //判断密码是否一致
        if(!StrUtil.equals(dto.getPassword(),dto.getConfirmPassword())){
            throw new HtException("密码输入不一致！");
        }
        SysUser sysUser=new SysUser();
        sysUser.setUsername(dto.getUsername());
        sysUser.setName(dto.getUsername());
        sysUser.setPassword(dto.getPassword());
        sysUser.setState(DicConstants.State.ENABLE);
        sysUserService.saveObj(sysUser);
        //设置用户角色
        SysRole sysRole = sysRoleService.getRoleByCode(DicConstants.RoleCode.USER);
        //保存角色
        sysUserRoleService.save(new SysUserRole().setRoleId(sysRole.getId()).setUserId(sysUser.getId()));
        return JsonResult.success();
    }




    /*
     * @param randomStr:随机字符串
     * @Author hejialun
     * @Description: TODO(创建验证码)
     * @date 2021/5/25 9:55
     * @returns com.ht.util.JsonResult
     */
    @GetMapping(value = "/getCode")
    public JsonResult getCode(String randomStr) throws Exception {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = captcha.text();
        // 保存
        redisUtil.set(RedisConstants.VERIFICATION_CODE_PREFIX+randomStr,result,BusConstant.VERIFICATION_CODE_OVERDUE_TIME);
        return JsonResult.success(captcha.toBase64());

    }
}